package com.cqq.common.core.mybatis.handler;

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
//import org.apache.ibatis.type.MappedJdbcTypes;
//import org.apache.ibatis.type.MappedTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//@MappedTypes(String[].class)
//@MappedJdbcTypes(JdbcType.ARRAY)
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

	private static final Logger log = LoggerFactory.getLogger(StringArrayTypeHandler.class);
	
	private static final String TYPE_NAME_VARCHAR = "varchar";

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
		String typeName = TYPE_NAME_VARCHAR;
		Connection conn = ps.getConnection();
		if(parameter==null){
			ps.setArray(i, null);
		}
		else{
			Array array = conn.createArrayOf(typeName, parameter);
			ps.setArray(i, array);
		}
	}

	@Override
	public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return getArray(rs.getArray(columnName));
	}

	@Override
	public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return getArray(rs.getArray(columnIndex));
	}

	@Override
	public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return getArray(cs.getArray(columnIndex));
	}

	private String[] getArray(Array array) {
		if (array == null) {
			return null;
		}
		try {
			return (String[]) array.getArray();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}
}
